package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
)

// 获取签约记录信息
func GetMiniProgramContractInfo(p map[string]interface{}) *models.MiniProgramContract {
	o := orm.NewOrm()
	miniProgramContract := &models.MiniProgramContract{}
	qs := o.QueryTable("MiniProgramContract")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["contract_code"]; ok {
		qs = qs.Filter("contract_code", p["contract_code"])
	}
	qs.One(miniProgramContract)
	return miniProgramContract
}

// 添加签约记录信息
func AddMiniProgramContract(input url.Values) (int64, error) {
	o := orm.NewOrm()
	miniProgramContract := &models.MiniProgramContract{}

	user := &models.User{}
	if _, ok := input["user_id"]; ok {
		user.Id = utils.Atoi64(input["user_id"][0])
		o.Read(user)
	}
	miniProgramContract.User = user
	if _, ok := input["contract_code"]; ok {
		miniProgramContract.ContractCode = input["contract_code"][0]
	} else {
		miniProgramContract.ContractCode = GetContractCode()
	}
	if _, ok := input["status"]; ok {
		miniProgramContract.Status, _ = strconv.Atoi(input["status"][0])
	}
	return o.Insert(miniProgramContract)
}

// 获取唯一签约协议号
func GetContractCode() string {
	contractCode := utils.GetSn()
	p := map[string]interface{}{}
	p["contract_code"] = contractCode
	record := GetMiniProgramContractInfo(p)
	for record.Id > 0 {
		contractCode = utils.GetSn()
		p["contract_code"] = contractCode
		record = GetMiniProgramContractInfo(p)
	}
	return contractCode
}

// 修改签约记录信息
func EditMiniProgramContract(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("MiniProgramContract").Filter("id", input["id"][0]).Update(p)
}

// 获取签约记录列表
func GetMiniProgramContractList(p map[string]interface{}) (int64, []*models.MiniProgramContract) {
	var miniProgramContractList []*models.MiniProgramContract
	o := orm.NewOrm()
	qs := o.QueryTable("MiniProgramContract")
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&miniProgramContractList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, miniProgramContract := range miniProgramContractList {
			miniProgramContract.CreatedShow = miniProgramContract.Created.Format("2006-01-02 15:04:05")
			miniProgramContract.StatusShow = models.MiniProgramContractStatus[miniProgramContract.Status]
		}
	}
	return totalCount, miniProgramContractList
}